const Sequelize = require('sequelize')
const ArticleModel = require('../model/ArticleModel')
const { SUCCESS_RESPONSE, PORT, HOST } = require('../config/index.js')
const path = require('path')
const fs = require('fs')

// 定义uploads目录路径
const UPLOADS_DIR = path.join(__dirname, '../uploads')

// 分类文章总数
exports.getCateArticleCount = async (req, res) => {
  let sql = `
    SELECT t1.category_name,count(*) as count FROM 
      category t1 LEFT JOIN article t2 ON t1.category_id = t2.category_id
      GROUP BY t1.category_id
  `
  // 查询
  const result = await req.db.sequelize.query(sql, {
    type: Sequelize.QueryTypes.SELECT,
  })
  res.json(SUCCESS_RESPONSE(result))
}

exports.addArticle = async (req, res) => {
  console.log('~~~~~~~addArticle~~~~~~')
  let result = await ArticleModel.insertArticle(req.body)
  if (result.affectedRows) {
    res.json(SUCCESS_RESPONSE({}, '添加文章成功'))
  } else {
    res.json(FAIL_RESPONSE({}, '添加文章失败', '00007'))
  }
}

// 文章分页列表接口
exports.articleList = async (req, res) => {
  // 1. 接收参数，所有的查询字符串req.query接收的值都是字符串string类型
  let { page = 1, pagesize = 2 } = req.query
  page = parseInt(page)
  pagesize = parseInt(pagesize)
  let offset = (page - 1) * pagesize
  // 2. 查询分页数据
  let { count, rows } = await req.db.article.findAndCountAll({
    raw: true,
    offset,
    limit: pagesize,
  })

  // 3. 查询符合条件的总记录数
  rows = rows.map((item) => {
    if (item.cover) {
      item.cover = `${HOST}:${PORT}/${item.cover}`
    }
    return item
  })
  // 4. 成功返回数据
  res.json(
    SUCCESS_RESPONSE({ count: count, article: rows }, '获取文章列表成功')
  )
}

// 获取所有图片文件的
exports.getImages = (req, res) => {
  // 读取uploads目录
  fs.readdir(UPLOADS_DIR, (err, files) => {
    // console.log(files)
    // 过滤出图片文件（可以根据需要扩展支持的格式）
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']
    const imageFiles = files.filter((file) => {
      const ext = path.extname(file).toLowerCase()
      return imageExtensions.includes(ext)
    })

    // 构建完整的URL路径
    const baseUrl = `${HOST}:${PORT}/uploads/`
    const imageUrls = imageFiles.map((file) => ({
      name: file,
      url: baseUrl + file,
    }))

    // 返回JSON响应
    res.json({
      code: '00000',
      data: {
        count: imageUrls.length,
        images: imageUrls,
      },
      msg: '请求成功',
    })
  })
}

// 删除指定图片文件
exports.delImages = (req, res) => {
  const { filename } = req.query

  // 验证请求参数
  if (!filename) {
    return res.status(400).json({
      error: 'Filename is required',
    })
  }

  // 构建文件路径
  const filePath = path.join(UPLOADS_DIR, filename)

  // 检查文件是否存在
  if (!fs.existsSync(filePath)) {
    return res.status(404).json({
      msg: 'File not found',
    })
  }

  // 删除文件
  fs.unlink(filePath, (err) => {
    if (err) {
      console.error('Error deleting file:', err)
      return res.status(500).json({
        msg: 'Failed to delete file',
      })
    }

    res.json({
      code: '00000',
      msg: 'File deleted successfully',
      data: filename,
    })
  })
}
